<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mall:cooperation:channel:add']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bannerList">
      <el-table-column label="渠道名称" align="center" prop="channelName" />
      <el-table-column label="渠道入口图" align="center" prop="channelImgPath	">
        <template slot-scope="scope">
          <img :src="scope.row.channelImgPath" class="avatar" />
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mall:cooperation:channel:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mall:cooperation:channel:remove']"
            >删除</el-button
          >
          <el-button size="mini" type="text" @click="handleCategory(scope.row)"
            >获取关联分类</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 分类列表 -->
    <el-dialog
      title="关联分类"
      :visible.sync="openCategory"
      width="800px"
      append-to-body
    >
      <el-form ref="cForm" :model="cForm" label-width="100px">
        <el-form-item label="分类列表">
          <el-tree
            class="tree-border"
            :data="deptOptions"
            show-checkbox
            ref="dept"
            node-key="id"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          :loading="submitCategoryLoading"
          @click="submitCategory"
          >确 定</el-button
        >
        <el-button @click="openCategory = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改商城首页轮播图对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- <el-form-item label="父级id" prop="pid">
          <el-input v-model="form.pid" placeholder="请输入父级id" />
        </el-form-item> -->
        <el-row :gutter="20">
          <el-col :span="13">
            <el-form-item label="渠道名称" prop="channelName">
              <el-input
                v-model="form.channelName"
                placeholder="请输入渠道名称"
              />
            </el-form-item>

            <el-form-item label="渠道入口图" prop="channelImgPath">
              <ImageUpload
                v-model="form.channelImgPath"
                :limit="1"
                @input="handleUploadUrl"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  bpList,
  addBp,
  editBp,
  delBp,
  getBp,
  getChannelCategory,
  getAllCategory,
  submitCategoryProxy,
} from "@/api/mallGuan/channel";
import ImageUpload from "@/components/ImageUpload";
export default {
  name: "Channel",
  components: {
    ImageUpload,
  },
  data() {
    return {
      openGoods: false,

      selectedProductList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      fileList: [],
      // 总条数
      total: 0,
      // 商城首页轮播图表格数据
      bannerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bannerName: null,
      },
      // 表单参数
      form: {
        bannerName: null,
      },

      // 表单校验
      rules: {},
      // 关联分类
      openCategory: false,
      // 部门列表
      deptOptions: [],
      defaultProps: {
        children: "children",
        label: "title",
      },
      // 关联分类
      cForm: {},
      submitCategoryLoading: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 提交分类
    submitCategory() {
      const checkedKeys = this.getDeptAllCheckedKeys();
      this.submitCategoryLoading = true;
      const data = [];
      checkedKeys.forEach((item) => {
        data.push({
          oneProductCategoryId: item,
          showSort: 50,
        });
      });
      submitCategoryProxy(this.cForm.id, data)
        .then((response) => {
          this.$modal.msgSuccess("提交成功");
          this.openCategory = false;
          this.getList();
          this.submitCategoryLoading = false;
        })
        .catch(() => {
          this.submitCategoryLoading = false;
        });
    },
    // 获取关联分类
    async handleCategory(row) {
      this.openCategory = true;
      const res = await getAllCategory();
      this.deptOptions = res.data;
      const res2 = await getChannelCategory(row.id);
      const checkedKeys = res2.data.map((item) => item.oneProductCategoryId);
      this.$refs.dept.setCheckedKeys(checkedKeys);
      this.cForm = {
        id: row.id,
      };
    },
    // 所有分类节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的分类节点
      let checkedKeys = this.$refs.dept.getCheckedKeys();
      // 半选中的分类节点
      // let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
      // checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    /** 查询商城首页轮播图列表 */
    getList() {
      this.loading = true;
      bpList(this.queryParams).then((response) => {
        this.bannerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 商家状态修改
    handleStatusChange(row) {
      console.log(row);
      const { id, isShelf } = row;
      let text = row.isShelf == 1 ? "上架" : "下架";
      this.$modal
        .confirm("确认要" + text + "" + row.bannerName + "吗？")
        .then(function () {
          return changeUpdateIsShelf({ id, isShelf });
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.isShelf = row.isShelf == 1 ? 0 : 1;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    handleUploadUrl(val) {
      this.form.channelImgPath = val;
    },
    // 表单重置
    reset() {
      this.form = {
        channelName: null,
        channelImgPath: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getBp(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form);
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            editBp(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBp(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除商城首页轮播图编号为"' + ids + '"的数据项？')
        .then(function () {
          return delBp(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "banner/export",
        {
          ...this.queryParams,
        },
        `banner_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang="less" scoped>
.tree-border {
  height: 500px;
  overflow-y: auto;
}
.el-radio {
  margin-right: 20px;
}
.img {
  width: 80px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  margin: 0 auto;
}
.avatar-uploader .el-upload {
  border: 1px dashed #ccc;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  border: 1px dashed #ccc;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}
.avatar {
  width: 148px;
  height: 148px;
  display: block;
  margin: 0 auto;
}
</style>
